<template>
  <ContentWrap >
    <el-descriptions :column="7">
      <el-descriptions-item label="合同编号">
        {{ projectData.contractNo || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="委托单位">
        {{ projectData.companyName || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="项目类型">
        {{ projectData.projectType || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="紧急程度">
        <dict-tag :type="DICT_TYPE.URGENCY_DEGREE" :value="projectData.urgencyLevel" />
      </el-descriptions-item>
      <el-descriptions-item label="项目状态">
        <dict-tag :type="DICT_TYPE.PROJECT_STATUS" :value="projectData.status" />
      </el-descriptions-item>

      <el-descriptions-item>
        <div class="button-group">
          <el-tooltip :content="sketchContent" placement="top">
            <el-button v-show="sketch" type="primary" @click="emit('sketch')">测点示意图</el-button>
          </el-tooltip>
          <el-tooltip :content="uploadContent" placement="top">
            <el-button v-show="upload" type="primary" @click="emit('upload')">导入</el-button>
          </el-tooltip>
          <el-tooltip :content="addRowContent" placement="top">
            <el-button v-show="addRow" type="primary" @click="emit('add-row')">新增</el-button>
          </el-tooltip>
          <el-button v-show="resetSampleNo" type="primary" @click="emit('reset-sample-no')">重置编号</el-button>
          <el-tooltip :content="syncContent" placement="top">
            <el-button v-show="sync" type="primary" @click="emit('on-sync-header')">同步</el-button>
          </el-tooltip>
          <el-button v-show="delivery" type="primary" @click="emit('delivery')">交样</el-button>
          <el-tooltip :content="signContent" placement="top">
            <el-button v-show="sign" type="primary" @click="toSignature">签名</el-button>
          </el-tooltip>
          <el-button v-show="preview" type="primary" @click="emit('preview-file')">预览</el-button>
        </div>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>
  <Signature
    :projectId="`${route.query.projectId}`"
    :reportType="reportType"
    ref="signatureRef"
  />
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ProjectApi } from '@/api/dk/project'
import { DICT_TYPE } from '@/utils/dict'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import Signature from '@/views/project/list/Signature.vue'

defineOptions({ name: 'ProjectInfo' })

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const activeTab = ref('basicInfo')
const projectData = ref<any>({})
const signatureRef = ref()
const props = defineProps({
  sync: {
    type: Boolean,
    default: false
  },
  preview: {
    type: Boolean,
    default: false
  },
  // 定性新增
  addRow: {
    type: Boolean,
    default: false
  },
  // 定性编号重置
  resetSampleNo: {
    type: Boolean,
    default: false
  },
  // 定性交样
  delivery: {
    type: Boolean,
    default: false
  },
  sign: {
    type: Boolean,
    default: false
  },
  upload: {
    type: Boolean,
    default: false
  },
  sketch: {
    type: Boolean,
    default: false
  },
  projectId: String,
  syncContent: String,
  uploadContent: String,
  addRowContent: String,
  sketchContent: String,
  signContent: {
    type: String,
    default: '签名'
  },
  reportType: String,
  // 是否需要签名校验（为 true 时，由父组件控制是否显示签名弹窗）
  needSignatureCheck: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['on-sync-header', 'preview-file', 'add-row', 'reset-sample-no', 'delivery','upload','sketch','signature'])

const toSignature = () => {
  emit('signature')
  
  // 如果不需要校验（默认情况），直接显示签名弹窗（保持向后兼容）
  // 如果需要校验，则等待父组件在 handleSignature 中调用 showSignatureDialog
  if (!props.needSignatureCheck) {
    showSignatureDialog()
  }
}

// 暴露给父组件的方法：显示签名弹窗
const showSignatureDialog = () => {
  if (signatureRef.value) {
    signatureRef.value.showDialog()
  }
}

// 暴露方法给父组件
defineExpose({
  showSignatureDialog
})

// 获取项目详情
const getProjectInfo = async () => {
  try {
    const response = await ProjectApi.getProject(Number(props.projectId))
    projectData.value = response || {}
  } catch (error) {
    console.error('获取项目信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 从 localStorage 恢复上次选中的 tab
const restoreActiveTab = () => {
  const savedTab = localStorage.getItem('project-info-active-tab')
  if (savedTab) {
    activeTab.value = savedTab
  }
}

// 保存当前选中的 tab 到 localStorage
const saveActiveTab = () => {
  localStorage.setItem('project-info-active-tab', activeTab.value)
}

// 监听 tab 变化
watch(() => activeTab.value, saveActiveTab)

onMounted(async () => {
  restoreActiveTab()
  await getProjectInfo()
})
</script>

<style scoped>

:deep(.el-descriptions__table td) {
  padding: 0px !important;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* 按钮样式优化 */
.button-group .el-button {
  margin: 0;
}
</style>
